const userModel = require("../model/user.model");
const { Op } = require("sequelize");
class UserServer {
  async createUser(params) {
    // const jane = await userModel.bulkCreate([
    //   { username: `${Math.ceil(Math.random() * 1000)}`, password: "14124123" },
    //   { username: `${Math.ceil(Math.random() * 1000)}`, password: "14124123" },
    //   { username: `${Math.ceil(Math.random() * 1000)}`, password: "14124123" },
    // ]);
    const user = userModel.create(params);
    return user;
    // const incrementResult = await jane.increment('age', { by: 2 });
    // console.log("创建成功");
  }
  async findUsers(params, isAdmin = false) {
    const where = {};
    params.username && (where.username = { [Op.like]: `%${params.username}%` });
    params.phone && (where.phone = params.phone);
    params.gender && (where.gender = params.gender);
    params.isAdmin && (where.isAdmin = params.isAdmin);
    !isAdmin && (where.isAdmin = 0); // 非管理员只能查非管理员用户
    const query = { attributes: { exclude: ["password"] }, where };
    if (params.page && params.size) {
      query.offset = parseInt((params.page - 1) * params.size);
      query.limit = parseInt(params.size);
      const { count, rows } = await userModel.findAndCountAll(query);
      return {
        page: parseInt(params.page),
        size: parseInt(params.size),
        list: rows,
        count,
      };
    }
    const users = await userModel.findAll(query);
    return users;
  }
}
module.exports = new UserServer();
